package com.scu.phototab.service;

import com.scu.phototab.bean.MailRecord;
import com.scu.phototab.repository.MailRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Locale;

/**
 * Created by tianfei on 2017/5/17.
 */
@Component
public class MailServiceImpl{

    private static Logger logger= LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    private MailRepository repository;

    @Autowired
    private SpringTemplateEngine engine;

    public void sendTokenMail(String token,String emailTo) throws MessagingException{

        new Thread(new Runnable() {
            @Override
            public void run(){

                final MailRecord record=new MailRecord();
                record.setCreateTime(new Date(System.currentTimeMillis()));
                record.setEmailAddrTo(emailTo);

                final Context ctx = new Context();
                ctx.setLocale(Locale.CHINA);
                ctx.setVariable("token",token);

                final MimeMessage message= sender.createMimeMessage();

                try {
                    final MimeMessageHelper helper=new MimeMessageHelper(message,true,"UTF-8");

                    helper.setTo(emailTo);
                    helper.setSubject("【我的标签】找回密码");
                    helper.setFrom(username);

                    final String htmlContent=engine.process("emailTemplate",ctx);
                    helper.setText(htmlContent,true);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    logger.error(e.toString());
                    record.setSendResult(false);
                }

                sender.send(message);
                record.setSendResult(true);
                repository.save(record);
            }
        }).start();

    }
}
